# Filter gapminder data for a specific year (e.g., 2007)
gapminder_2007 <- gapminder |>
filter(year == 2007) |>
select(country, lifeExp)
# Get world map data
world_sf <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf") |>
select(name, geometry)
# Ensure the CRS is WGS 84 (Leaflet's requirement)
world_sf <- st_transform(world_sf, crs = 4326)
# Handle potential country name mismatches
world_sf <- world_sf |>
mutate(name = recode(name,
"United States" = "United States of America",
"Congo" = "Congo, Rep.",
"Democratic Republic of Congo" = "Congo, Dem. Rep.",
"Slovakia" = "Slovak Republic",
"Myanmar" = "Burma",
"Egypt" = "Egypt, Arab Rep.",
"Yemen" = "Yemen, Rep."))
# Merge the datasets
map_data <- world_sf |>
left_join(gapminder_2007, by = c("name" = "country")) |>
# Remove countries with no life expectancy data in the chosen year
filter(!is.na(lifeExp))
# Define a color palette
pal <- colorNumeric("RdYlGn", domain = map_data$lifeExp)
# Create the map
leaflet(data = map_data) |>
addProviderTiles(providers$CartoDB.Positron) |> # Add a base map tile
addPolygons(
fillColor = ~pal(lifeExp),
weight = 1,
opacity = 1,
color = "white",
dashArray = "3",
fillOpacity = 0.7,
highlight = highlightOptions(
weight = 3,
color = "#666",
dashArray = "",
fillOpacity = 0.9,
bringToFront = TRUE),
popup = ~paste0("<strong>", name, "</strong><br/>Life Expectancy: ", round(lifeExp, 2), " years") # Add interactive popups
) |>
addLegend(pal = pal, values = ~lifeExp, opacity = 0.7, title = "Life Expectancy (Years)",
position = "bottomright")